<?php
/**
  * tframe
  *
  *
  * @copyright Copyright (c) 2012 - 2014, huxiaomin
  * @author huxiaomin    2012-5-29  
  * @since		Version 1.0
  *
  */

class TLog{

	private $table;
	
    function __construct(){
        
    }
    
    /**
     * 记录数据库日志
     * 推荐默认key1使用uri
     * @param $data
     * @param $key1 为空就取文件名 
     * @param $key2 为空就取类名加方法名
     * @param $key3
     */
    static function logDb($data='',$key1='',$key2='',$level='app'){
    	if (is_array($data) || is_object($data)){
    	   $data = json_encode($data);
    	}
    	if (empty($key1) || empty($key2)){
    	   $trace = self::getTrace();
    	   if (!$key1){
    	       $key1 = $trace['key1'];
    	   }
    	   if (!$key2){
               $key2 = $trace['key2'];
           }
    	}
    	
    	$table = new TTable('dlog');
        $log = array(
                     'data'=>$data,
                     'key1'=>$key1,
                     'key2'=>$key2,
                     'level'=>$level,
                     'add_time'=>date('Y-m-d H:i:s'),
                    );
        return $table->insert($log);
    }
    
    /**
     * 记录日志到文件中
     * @param $data
     * @param $key1
     * @param $key2
     * @param $level
     */
    static function logFile($data='',$key1='',$key2='',$level='app'){
        if (empty($key1) || empty($key2)){
           $trace = self::getTrace();
           if (!$key1){
               $key1 = $trace['key1'];
           }
           if (!$key2){
               $key2 = $trace['key2'];
           }
        }
        $log = array(
                     'data'=>$data,
                     'key1'=>$key1,
                     'key2'=>$key2,
                     'level'=>$level,
                    );
        file_put_contents(TLOG_DIR.date('Y-m').'log.html', 
                  'add_time:'.date('Y-m-d H:i:s')."{$key1}:{$key2}\n".
                   json_encode($log)."\n", FILE_APPEND);            
    }
    
    /**
     * 临时记录 只记两个月的记录
     * @param $data
     */
    static function logTemp($data,$file_name='temp'){
    	$trace = self::getTrace();
    	$data = print_r($trace,1).print_r($data,1);
    	$m = date('m')%3;
    	$check = ($m+1)%3;
    	$check = TLOG_DIR.'logTemp_'.$file_name.'_'.$check.'.log.html';
    	if (file_exists($check)){
    		unlink($check);
    	}
    	file_put_contents(TLOG_DIR.'logTemp_'.$file_name.'_'.$m.'.log.html', $data, FILE_APPEND);
    }
    
    
    static function getTrace($num=2){
        $str = debug_backtrace();
        $str = $str[$num];
        return array('key1'=>basename($str['file']),
                      'key2'=>$str['class'].'.'.$str['function']);
    }
	
}